<template>
  <Dialog
    :title="dialogTitle"
    v-model="dialogVisible"
    width="70%"
    center
    align-centers
    :fullscreen="false"
    @close="cancel"
  >
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      ref="queryFormRef"
      :model="queryParams"
      :inline="true"
      label-width="auto"
      :rules="queryFormRules"
    >
      <el-form-item label="进料日期" prop="feedTime">
        <el-date-picker
          v-model="queryParams.feedTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-200px"
          unlink-panels
        />
      </el-form-item>
      <el-form-item label="物资分类" prop="goodsType">
        <el-input
          v-model="queryParams.goodsType"
          placeholder="请输入"
          clearable
          @keyup.enter="handleQuery"
          class="!w-150px"
        />
      </el-form-item>
      <el-form-item label="物资名称" prop="goodsName">
        <el-input
          v-model="queryParams.goodsName"
          placeholder="请输入"
          clearable
          @keyup.enter="handleQuery"
          class="!w-150px"
        />
        <el-button class="ml-10px" @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" />
          搜索
        </el-button>
      </el-form-item>
    </el-form>

    <div class="mt-10px mb-10px">
      <el-table
        :data="list"
        :border="true"
        :stripe="true"
        :show-overflow-tooltip="true"
        height="300"
        ref="tableRef"
        @row-click="handleRowClick"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" align="center" min-width="40" />
        <el-table-column label="项目名称" align="center" prop="projectName" min-width="100" />
        <el-table-column
          label="进料日期"
          align="center"
          prop="feedTime"
          min-width="110"
          :formatter="dateFormatter2"
        />
        <el-table-column label="供应商名称" align="center" prop="supplierName" min-width="100" />
        <el-table-column label="物资分类" align="center" prop="goodsType" min-width="100" />
        <el-table-column label="物资名称" align="center" prop="goodsName" min-width="100" />
        <el-table-column label="规格型号" align="center" prop="goodsModel" min-width="100" />
        <el-table-column label="计量单位" align="center" prop="unit" min-width="70" />
        <el-table-column label="数量" align="center" prop="quantity" min-width="100" />
        <el-table-column label="不含税单价" align="center" prop="price" min-width="100" />
        <el-table-column label="税率" align="center" prop="taxRate" min-width="100">
          <template #default="scope">{{ scope.row.taxRate }}% </template>
        </el-table-column>
        <el-table-column label="含税单价" align="center" prop="taxPrice" min-width="100" />
        <el-table-column label="含税金额" align="center" prop="taxTotalPrice" min-width="100" />
      </el-table>
      <div class="clearfix">
        <Pagination
          :total="total"
          v-model:page="queryParams.pageNo"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </div>
    </div>

    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="auto"
      v-loading="formLoading"
    >
      <el-row>
        <el-col :span="16">
          <el-form-item label="操作类型" prop="type">
            <el-radio-group v-model="formData.type">
              <el-radio value="1">满足当前查询条件的{{ total }}条数据</el-radio>
              <el-radio value="2">选择的{{ selectSize }}条数据</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="存放地点" prop="storageAddressId">
            <el-select
              v-model="formData.storageAddressId"
              placeholder="请选择"
              @change="selectStorageAddress"
            >
              <el-option
                v-for="(item, index) in simpleAddressList"
                :key="index"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="cancel">取 消</el-button>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">提 交</el-button>
    </template>
  </Dialog>
</template>
<script setup>
import { dateFormatter2 } from '@/utils/formatTime'
import { LedgerFeedMaterialApi } from '@/api/rep/ledger/feedmaterial'
import { StorageLocationApi } from '@/api/rep/ledger/storagelocation'

/** 存放地点初始化 表单 */
defineOptions({ name: 'StorageLocationForm2' })

const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('收料台账-存放地点') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = ref({
  type: '2',
  feedIds: [],
  storageAddressId: undefined,
  storageAddress: undefined,
  goodsType: undefined,
  goodsName: undefined,
  feedTime: []
})
const formRules = reactive({
  type: [{ required: true, message: '请选择操作类型', trigger: 'change' }],
  storageAddressId: [{ required: true, message: '请选择存放地点', trigger: 'change' }]
})

const queryFormRules = reactive({
  feedTime: [{ required: true, message: '请选择进料日期', trigger: 'change' }]
})

const formRef = ref() // 表单 Ref

/** 搜索参数 */
const queryParams = ref({
  pageNo: 1,
  pageSize: 10,
  goodsType: undefined,
  goodsName: undefined,
  feedTime: []
})
const queryFormRef = ref() // 搜索表单 Ref

const loading = ref(true) // 列表的加载中
const list = ref([]) // 列表的数据
const total = ref(0) // 列表的总页数
const selectSize = ref(0) // 列表的总页数

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await LedgerFeedMaterialApi.getAddressList(queryParams.value)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

// 存放地点下拉列表
const simpleAddressList = ref([])
/** 查询存放地点下拉列表 */
const getSimpleAddressList = async () => {
  const data = await StorageLocationApi.getSimpleAddressList()
  simpleAddressList.value = data
}
// 选择存放地点
const selectStorageAddress = (val) => {
  formData.value.storageAddressId = val
  formData.value.storageAddress = simpleAddressList.value.find((item) => item.id == val).name
}

/** 搜索按钮操作 */
const handleQuery = async () => {
  // 校验表单
  await queryFormRef.value.validate()
  queryParams.value.pageNo = 1
  getList()
}

/** 表格的选中数据发生变化 */
const handleSelectionChange = (selectList) => {
  formData.value.feedIds = selectList.map((item) => item.id)
  selectSize.value = selectList.length
}

/** 处理某一行的点击 */
const tableRef = ref()
const handleRowClick = (row) => {
  unref(tableRef)?.toggleRowSelection(row)
}

/** 打开弹窗 */
const open = () => {
  dialogVisible.value = true
  resetForm()
  list.value = []
  total.value = 0
  getSimpleAddressList()
  getList()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调

const cancel = () => {
  // 发送操作取消的事件
  emit('success')
  dialogVisible.value = false
}

const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()

  // 判断有没有选择数据
  if (formData.value.type === '1') {
    // 校验表单
    await queryFormRef.value.validate()

    await queryFormRef.value.validate()
    if (total.value === 0) {
      message.warning('满足当前查询条件的数据条数大于零时可操作！')
      return
    }

    if (total.value > 2000) {
      // 提交二次确认
      await message.confirm('满足当前查询条件的数据条数超过2000，需要多次操作！', '提交')
    }

    if (queryParams.value.feedTime && queryParams.value.feedTime.length > 0) {
      formData.value.feedTime[0] = new Date(queryParams.value.feedTime[0]).getTime()
      formData.value.feedTime[1] = new Date(queryParams.value.feedTime[1]).getTime()
    }

    formData.value.goodsType = queryParams.value.goodsType
    formData.value.goodsName = queryParams.value.goodsName
  } else {
    if (formData.value.feedIds.length == 0) {
      message.warning('请选择要修改的数据')
      return
    }
  }
  // 提交请求
  formLoading.value = true
  try {
    await LedgerFeedMaterialApi.batchStorageAddress(formData.value)
    message.success('提交成功')
    // dialogVisible.value = false
    // // 发送操作成功的事件
    // emit('success')
    getList()
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  // 搜索表单
  queryParams.value = {
    pageNo: 1,
    pageSize: 10,
    goodsType: undefined,
    goodsName: undefined,
    feedTime: []
  }
  queryFormRef.value?.resetFields()

  // 提交表单
  formData.value = {
    type: '2',
    feedIds: [],
    storageAddressId: undefined,
    storageAddress: undefined,
    goodsType: undefined,
    goodsName: undefined,
    feedTime: []
  }
  formRef.value?.resetFields()
}
</script>
<style lang="scss" scoped>
.clearfix::after {
  content: '';
  display: table;
  clear: both;
}
</style>
